import React from "react";
import css from './HelloWorld.less';

// 类型约束
type P = {
    message?: string;
}

type S = {
    count: number;
    currentTime: string;
}

let setTime: any = null

export default class HelloWorld extends React.Component<P, S> {
    // 属性默认值
    static defaultProps = {
        message: 'Hello, world!'
    }
    constructor(props: P) {
        super(props)
        // 状态管理
        this.state = {
            count: 1,
            currentTime: ''
        }
    }
    UNSAFE_componentWillMount() {
        this.getCurrentTime()
        this.addTime()
    }
    componentWillUnmount() {
        this.clearTime()
    }
    getCurrentTime = () => {
        const currentTime = new Date().toLocaleString()
        this.setState({ currentTime })
    }
    addTime() {
        if (setTime) {
            this.clearTime()
        }
        setTime = setInterval(() => {
            this.getCurrentTime()
        }, 1000)
    }
    clearTime() {
        if (setTime) {
            clearInterval(setTime)
            setTime = null
        }
    }
    userClick = () => {
        this.setState({
            count: this.state.count + 1
        })
    }
    render() {
        const { message } = this.props
        const { count, currentTime } = this.state
        return (
            <div className={css.hello_max}>
                <p className={css.head_title}> {message} </p>
                <p className={css.time_box}>当前时间: {currentTime}</p>
                <p>{count}</p>
                <button onClick={this.userClick}>点击</button>
            </div>
        )
    }
}